<?
//start fb-session
$_FB = new Facebook($_FACEBOOK);

function authentificate() {
	global $_FACEBOOK,$_MISC,$_FB,$_DB;
	//Get the rights&Auth_Code
	//~ if(!$_GET['code'] OR $_GET['error']) {
	if(!check_facebook_session()) {
		if($_GET['additional_rights']) $addrights=",{$_GET['additional_rights']}"; else $addrights="";
		$url=$_FB->getLoginUrl(array('req_perms' =>$_FACEBOOK['rights'].$addrights, 'redirect_uri'=>"{$_MISC['app-url']}/auth/facebook"));
		usession_set('tmp_fb_rights',$_FACEBOOK['rights'].$addrights);
		header("Location: $url");
		//~ header("Location: http://www.facebook.com/dialog/oauth/?scope={$_FACEBOOK['rights']}&client_id={$_FACEBOOK['appId']}&redirect_uri={$_MISC['app-url']}/auth/facebook");
		exit;
	}
	//check if the user already exists in our database and add him when not
	//in both cases, set the session-cookie to authentificated
	$userInfo = $_FB->api("/me");
	
	if(check_user_exists($userInfo['email'])) {
		$dbuserinfo=get_userInfo($userInfo['email']);
	}
		//~ list($town, $country) = explode(', ',utf8_decode($userInfo['location']['name']),2);
		//~ $query=$_DB->prepare('INSERT INTO `user` (`fbid`,   `name`, `email`,  `sex`, `locale`, `hometown`,   `country`,  `birthday`,  `rights`,  `regdate`,  `authtoken`) VALUES( :fbid, :name ,:email, :sex, :locale, :hometown, :country, :birthday, :rights, :regdate, :authtoken )');
		//~ $query->execute(array(
			//~ 'fbid'=>$userInfo['id'],
			//~ 'name'=>utf8_decode($userInfo['name']),
			//~ 'email'=>$userInfo['email'],
			//~ 'sex'=>$userInfo['gender'],
			//~ 'locale'=>$userInfo['locale'],
			//~ 'hometown'=>$town,
			//~ 'country'=>$country,
			//~ 'birthday'=>date('Y-m-d',strtotime($userInfo['birthday'])),
			//~ 'rights'=> 0,  //  $_FACEBOOK['rights'],
			//~ 'regdate'=>date('Y-m-d H:i:s'),
			//~ 'authtoken'=>$_FB->getAccessToken()));
		//~ print_r($query->errorInfo());
		if(!$dbuserinfo['auth_facebook']==1) {
			updateAndSetUserData($userInfo['email'],array(
				'auth_facebook'=>1,
				'fbid'=>$userInfo['id'],
				'name'=>utf8_decode($userInfo['name']),
				'email'=>$userInfo['email'],
				'sex'=>$userInfo['gender'],
				'locale'=>$userInfo['locale'],
				'hometown'=>$town,
				'country'=>$country,
				'birthday'=>date('Y-m-d',strtotime($userInfo['birthday'])),
				'regdate_facebook'=>date('Y-m-d H:i:s'),
				'regdate_first'=>$_SESSION['regdate_first'],
				'rights'=>usession_get('tmp_fb_rights'),
				'authtoken'=>$_FB->getAccessToken()));
				
				
				/*PUBLISH TO WALL*/
				if(stristr(usession_get('tmp_fb_rights'),'publish_stream')) {
					$message="In Legend published a facebook app that enables you to listen to their new album. I am doing it right now! What's your opinion on the songs?";
					$attachment = array(
						 'name' => 'Listen to Ballads n Bullets by In Legend. Now!',
						 'link' => 'http://goo.gl/PxWXA',
						 'description' => 'Ballads N Bullets will be available May 20th 2011',
						 'picture' => 'http://fbapp.rene-pickhardt.de/images/IL_150.jpg',
						);
					$action_links = array( array('name' => 'balladsnbullets', 'link' => 'http://goo.gl/PxWXA'));
					publish_to_wall($message,$attachment,$action_links);
				}
			}
		//}
	//~ print_r($userInfo);
	usession_set('authentificated', true);
	usession_set('email', $userInfo['email']);
	usession_set('auth_mode', 'facebook');		
	//everything is ok, redirect the user back
	//header("Location: {$_MISC['app-url']}?".rand());
	?><script type="text/javascript">window.close()</script><?
	exit();
	//~ echo "user exists: ", check_user_exists($userInfo['email'])?"yes":"no";
	//~ echo "<br>fb-access-token: ", $_FB->getAccessToken();
	//~ echo "<br>";
}

function check_facebook_session() {
	global $_FB;
	if ($_FB->getSession()) {
		try {
			$uid = $_FB->getUser();
			$me = $_FB->api('/me');
			return true;
		} catch (FacebookApiException $e) {
			return false;
		}
	} else {
		return false;
	}
}


function publish_to_wall($message,$attachment=array(),$actions_links=array(),$publishto="me") {
	global $_FB;
	$attachment['message']=$message;
	$attachment['actions']=$actions_links;
    $result = $_FB->api("/$publishto/feed/",'post', $attachment); 
 }


?>